package com.hxy.manager.activity.goods;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.hxy.manager.R;
import com.hxy.manager.activity.CaptureActivity;
import com.hxy.manager.activity.ViewHolder;
import com.hxy.manager.entity.GoodsEntity;
import com.hxy.manager.service.GoodsEntityService;
import com.hxy.manager.service.SyncService;
import com.hxy.manager.util.Constant;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 傲寒宏志 on 2017/12/31.
 * <p>
 * 库存
 */

public class GoodsStoreActivity extends Activity {

    List<GoodsEntity> userList = new ArrayList<>();

    public static GoodsStoreActivity goodsStoreActivity;
    /**
     * 结果列表
     */
    private ListView listView;

    /**
     * ListView列表适配器
     */
    private BaseAdapter listViewAdapter;

    // 当前选择
    private int selecteItem = 0;

    // 判断是查询还是添加

    int flag = 0;

    int i = 0;// 用于判断是点击了查询还是其他，然后决定返回键的作用


    private SyncService syncService;

    BroadcastReceiver receiver = null;

    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setTitle("库存商品");
        setContentView(R.layout.store);
        getActionBar().setDisplayHomeAsUpEnabled(true);// 向上返回
        listView = (ListView) findViewById(R.id.listView1);
        goodsStoreActivity = this;
        loadBook();

        // ActionBar actionBar=getActionBar();
        // actionBar.show();
        // 绑定同步服务。
        // 当Activity退出后，也就取消了绑定服务。

        final Intent serviceIntent = new Intent(GoodsStoreActivity.this, SyncService.class);
        bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
        log.info("\n===>注册了广播");

        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String s = intent.getExtras().getString(Constant.MESSAGE);
                log.info("\n===>广播接收到信息[{}]",s);
                userList = GoodsEntityService.listAll(GoodsStoreActivity.this);
                // 刷新列表
                listViewAdapter.notifyDataSetChanged();
                Toast.makeText(GoodsStoreActivity.this, "更新成功！", Toast.LENGTH_SHORT).show();
                if ("postexception".equals(s)) {
                    Toast.makeText(GoodsStoreActivity.this, "网络异常！", Toast.LENGTH_SHORT).show();
                } else
                    Toast.makeText(GoodsStoreActivity.this, s, Toast.LENGTH_LONG).show();

            }
        };
        IntentFilter filter = new IntentFilter(Constant.BROADCAST_ACTION);
        registerReceiver(receiver, filter);
        log.info("\n===>注册完了广播");
    }

    // 绑定服务
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            syncService = ((SyncService.LocalBinder) iBinder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            syncService = null;
        }
    };

    /**
     * 修改后重新加载
     */

    @Override
    protected void onResume() {
        super.onResume();

        userList = GoodsEntityService.listAll(this);
        // 刷新列表

        listViewAdapter.notifyDataSetChanged();
    }

    // 返回键的监听
    @Override
    public void onBackPressed() {
        // super.onBackPressed();//这个方法会自动调用finish()，屏蔽掉。
        // Toast.makeText(Store.this,"按下了back键
        // onBackPressed()",Toast.LENGTH_SHORT).show();
        Log.i("kan", "按下了back键   onBackPressed()");

        // 点击了查询，后的结果，然后点击返回，再返回到所有数据的列表
        if (flag == 1 && i == 0) {
            i++;
            userList = GoodsEntityService.listAll(this);
            // 刷新列表
            listViewAdapter.notifyDataSetChanged();
        } else
            finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home: // 默认添加的
                finish();
                break;
            case R.id.action_add:// 保存
                startActivity(new Intent(GoodsStoreActivity.this, GoodsAddActivity.class));
                // Toast.makeText(Store.this,"点击了添加！",Toast.LENGTH_SHORT).show();
                flag = 0;
                break;
            case R.id.action_scan:
                // Toast.makeText(this, "点击了扫码！", Toast.LENGTH_LONG).show();

                if (ContextCompat.checkSelfPermission(GoodsStoreActivity.this,
                        Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(GoodsStoreActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
                } else {
                    startActivityForResult(new Intent(GoodsStoreActivity.this, CaptureActivity.class), 0);
                }
                flag = 0;
                break;
            case R.id.action_find:
                // Toast.makeText(this, "点击了查询！", Toast.LENGTH_LONG).show();
                new FindDialog(this).show();
                flag = 1;
                break;
            case R.id.action_statistics:
                AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
                builder1.setTitle("统计");
                // 04 builder.setIcon(R.drawable.scan);
                // 下一步进行主页面adapter的列表自定义。

                int size = userList.size();
                if (size == 1 && userList.get(0).getName().contains("数据为空")) {
                    builder1.setMessage("当前没有库存商品");
                } else {
                    builder1.setMessage("共计：" + size + " 种商品");
                }

                builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        // TODO Auto-generated method stub
                    }
                });
                builder1.create();
                builder1.show();
                break;
            /*
             * case R.id.action_about:
             *
             * AlertDialog.Builder builder= new AlertDialog.Builder(this);
             * builder.setTitle("关于"); //04 builder.setIcon(R.drawable.scan);
             * //下一步进行主页面adapter的列表自定义。
             *
             * builder.setMessage("版本：1.17.5\n作者：aohanhongzhi@qq.com\n日期：2018年3月16日"
             * ); builder.setPositiveButton("确定", new
             * DialogInterface.OnClickListener() {
             *
             * @Override public void onClick(DialogInterface arg0, int arg1) { //
             * TODO Auto-generated method stub } }); builder.create();
             * builder.show(); break;
             */
            case R.id.action_sync:
//                同步数据到服务器
                // Intent intent = new Intent(Store.this,MainService.class);
                // Toast.makeText(this, "点击了同步！", Toast.LENGTH_SHORT).show();
                // intent = new Intent(Store.this,SyncService.class);
                // startService(intent);
                if (syncService == null) {
                    Toast.makeText(this, "服务未绑定成功！", Toast.LENGTH_SHORT).show();
                    return false;
                } else {
                    Log.i("kan", "开始同步数据！");
//                    Toast.makeText(this, "开始同步数据！", Toast.LENGTH_SHORT).show();
                    syncService.uploadData();// 同步数据
                }

                break;
//            case R.id.action_nosync:
////                syncService.download();
//                Toast.makeText(this, "开始恢复数据！", Toast.LENGTH_SHORT).show();
//                break;
            /*
             * case R.id.action_settings: startActivity(new
             * Intent(Store.this,SettingActivity.class)); break;
             */

        }
        return false;

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            // Toast.makeText(this,"扫描结果："+bundle.getString("result"),Toast.LENGTH_LONG).show();
            // 查询数据库
            String scanCode = bundle.getString("result");
//            MakeTable mt = new MakeTable(Store.this);
//            GoodsEntity user = mt.getUserByNumber(scanCode);
            GoodsEntity oneByNumber = GoodsEntityService.getOneByNumber(this, scanCode);
            // 如果在数据库中不存在，那么就跳转到添加中
            if (oneByNumber == null) {
                Intent intent = new Intent(GoodsStoreActivity.this, GoodsAddActivity.class);
                intent.putExtra("scanCode", scanCode);
                startActivity(intent);
            } else {
                Intent intent = new Intent(GoodsStoreActivity.this, GoodsShowActivity.class);
                intent.putExtra("scanCode", scanCode);
                startActivity(intent);
                // Toast.makeText(this, "看看吧", Toast.LENGTH_LONG).show();

            }
        }
    }

    // 内部类？********************/
    public class FindDialog extends Dialog {

        public FindDialog(Context context) {
            super(context);
        }

        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.find);
            setTitle("查询");
            // 点击查询自动弹出虚拟键盘
            EditText value = (EditText) findViewById(R.id.value);
            value.setFocusable(true);
            value.setFocusableInTouchMode(true);
            value.requestFocus();
            this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

            Button find = (Button) findViewById(R.id.find);
            Button cancel = (Button) findViewById(R.id.cancel);
            find.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    EditText value = (EditText) findViewById(R.id.value);
                    String values = value.getText().toString();
                    /*
                     * //捕获异常的方法判断是否为数字 try{ Integer.parseInt(values);
                     *
                     *
                     *
                     * }catch(NumberFormatException e) { Log.i("kan","异常：\"" +
                     * values + "\"不是数字/整数...");
                     *
                     * }
                     */
                    userList = GoodsEntityService.getOneBySearch(GoodsStoreActivity.this, values);

                    // for(int i=0 ; i<users.length;i++){
                    // Toast.makeText(this,users[i].getName()+users[i].getMobile()
                    // ,Toast.LENGTH_LONG).show();
                    // }
                    listViewAdapter.notifyDataSetChanged();
                    selecteItem = 0;
                    dismiss();
                }
            });
            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    dismiss();
                }
            });
        }
    }

    public void loadBook() {

        // 获取所有通讯录联系人
//        MakeTable ct = new MakeTable(this);
//        users = ct.getAllData();
//        userList = GoodsEntityService.list();

        userList = GoodsEntityService.listAll(this);


        /*
         * 并没有解决逆序 for (int start = 0, end = users.length - 1; start < end;
         * start++, end--) { LeiXing temp = users[end]; users[end] =
         * users[start]; users[start] = temp; }
         */

        // listView列表实现适配器
        listViewAdapter = new BaseAdapter() {

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {

                // 逆序的实现，貌似会带来listView的卡顿。position是listview的位置。position2是的数据库的位置
                int position2 = userList.size() - 1 - position;

                // 加入,这个类是自定义的静态类。
                ViewHolder holder;

                if (convertView == null) {
                    /*
                     * TextView textView= new TextView(Store.this);
                     * textView.setTextSize(22); convertView=textView;
                     */

                    final LayoutInflater inflater = (LayoutInflater) getApplicationContext()
                            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    convertView = inflater.inflate(R.layout.item, null);
                    holder = new ViewHolder();
                    holder.icon = (ImageView) convertView.findViewById(R.id.imageView);
                    holder.name = (TextView) convertView.findViewById(R.id.nameView);
                    holder.price = (TextView) convertView.findViewById(R.id.priceView);
                    convertView.setTag(holder);

                } else {
                    holder = (ViewHolder) convertView.getTag();
                }

                /************************ 三元运算符 *****************************/
                // String price =
                // users[position].getPrice()==null?"":users[position].getPrice();
                // ((TextView)convertView).setText(""+users[position].getName()+"\n
                // "+position+"价格: "+price);
                // ((TextView)convertView).setText((position+1)+".书名："+users[position].getName()+"\n
                // "+"价格: "+price);

                holder.icon.setImageResource(R.drawable.store_logo);

                GoodsEntity goodsEntity = userList.get(position2);
                holder.name.setText(goodsEntity.getName());
                holder.price.setText(goodsEntity.getPrice());

                // position是listview的位置。
                if (position == selecteItem) {
                    convertView.setBackgroundColor(0x5f1296db);
                    // Toast.makeText(this, "text", Toast.LENGTH_LONG).show();
                } else {
                    convertView.setBackgroundColor(0);
                }
                return convertView;
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public Object getItem(int position) {
                return userList.get(position);
            }

            @Override
            public int getCount() {
                return userList.size();
            }
        };
        // 设置listView控件的适配器
        listView.setAdapter(listViewAdapter);
        // 长按
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                selecteItem = arg2;
                // 逆序的实现，貌似会带来listView的卡顿。
                int selecteItem2 = userList.size() - 1 - selecteItem;
                // Toast.makeText(Store.this,"长按修改",Toast.LENGTH_SHORT).show();
                GoodsEntity goodsEntity = userList.get(selecteItem2);
                if (goodsEntity.getNumber() != null) {
                    Intent intent3 = new Intent(GoodsStoreActivity.this, GoodsUpdateActivity.class);
                    intent3.putExtra("scanCode", goodsEntity.getNumber());
                    startActivity(intent3);
                } else {
                    Toast.makeText(GoodsStoreActivity.this, "没有数据", Toast.LENGTH_SHORT).show();
                }

                return true;

            }
        });
        // 短按
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                /*
                 * //记录单击列的位置 selecteItem=arg2; //刷新列表
                 * listViewAdapter.notifyDataSetChanged();
                 */

                selecteItem = arg2;
                // 逆序的实现，貌似会带来listView的卡顿。
                int selecteItem2 = userList.size() - 1 - selecteItem;
                GoodsEntity goodsEntity = userList.get(selecteItem2);

                String number = goodsEntity.getNumber();
                if (number != null) {
                    Log.i("kan", "当前" + number);
                    Intent intent3 = new Intent(GoodsStoreActivity.this, GoodsShowActivity.class);
                    intent3.putExtra("scanCode", number);
                    startActivity(intent3);
                } else {
                    Toast.makeText(GoodsStoreActivity.this, "空", Toast.LENGTH_SHORT).show();
                }

            }

        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        如果不取消就会造成内存泄露
        unregisterReceiver(receiver);//LS:重点！
        unbindService(mConnection);
        log.info("\n===>取消了广播");

    }

    Logger log = LoggerFactory.getLogger(GoodsStoreActivity.class);
}
